<?php
if(!defined('IN_WOGU')) {
    exit('Access Denied');
}

Loader::loadClass('Model');

class MenusModel extends Model
{
    protected $_table = 'menus';

    public function getMenus($where) {
        return $this->select($where, '*', '', '', '', 'id');
    }
    
    public function addMenu($data) {
        return $this->insert($data);
    }
    
    public function getMenu($where) {
        return $this->getOne($where);
    }
    
    public function deleteMenu($id) {
        $this->delete(array('id' => $id));

        $menus = $this->getMenus(array('parentid' => $id));
        foreach($menus as $menu) {
            $this->deleteMenu($menu['id']);
        }
    }
    
    public function updateMenu($data, $where) {
        return $this->update($data, $where);
    }
    
    public function updateChildMenus($pid, $excludeids, $includeids) {
        $menus = $this->getMenus(array('parentid' => $pid));
        foreach($menus as $menu) {
            if($menu['groupid'] == 0) {
                $this->updateMenu(array('groupid' => implode(',', $includeids)), array('id' => $menu['id']));
            } else {
                $ids = array();
                $groupids = explode(',', $menu['groupid']);
                foreach ($groupids as $v) {
                    if(!in_array($v, $excludeids)) {
                        $ids[] = $v;
                    }
                }
                
                $this->updateMenu(array('groupid' => implode(',', $ids)), array('id' => $menu['id']));
            }
            
            $this->updateChildMenus($menu['id'], $excludeids, $includeids);
        }
    }
    
    public function useSamePermissionToChildren($pid, $groupids) {
        $menus = $this->getMenus(array('parentid' => $pid));
        foreach($menus as $menu) {
            $this->updateMenu(array('groupid' => $groupids), array('id' => $menu['id']));
            $this->useSamePermissionToChildren($menu['id'], $groupids);
        }
    }
}